package com.mayikt;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author: maplefire
 * @Description: 使用BlockingQueue模拟生产者与消费者
 * @Date: 2022/09/02 10:20
 */

class ProducerThread extends Thread {

    private BlockingQueue<String> blockingQueue;
    private volatile boolean flag = true;
    AtomicInteger atomicInteger = new AtomicInteger();

    public ProducerThread(BlockingQueue<String> blockingQueue) {
        this.blockingQueue = blockingQueue;
    }

    @Override
    public void run() {
        System.out.println("生产者线程已经启动..");
        while (flag) {
            try {
                String data = atomicInteger.incrementAndGet() + "";
                boolean offer = blockingQueue.offer(data, 2, TimeUnit.SECONDS);
                if (offer) {
                    System.out.println("生产者插入队列成功,data:" + data);
                } else {
                    System.out.println("生产者插入队列失败,data:" + data);
                }
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                System.out.println("生产者已经结束");
            }
        }
    }

    public void stopThread() {
        this.flag = false;
    }
}

class ConsumerThread extends Thread {

    private BlockingQueue<String> blockingQueue;
    private volatile boolean flag = true;

    public ConsumerThread(BlockingQueue<String> blockingQueue) {
        this.blockingQueue = blockingQueue;
    }

    @Override
    public void run() {
        System.out.println("消费者线程已经启动..");
        while (flag) {
            try {
                String data = blockingQueue.poll(2, TimeUnit.SECONDS);
                if (data == null) {
                    System.out.println("消费者超过2s，队列取值失败");
                    flag = false;
                    return;
                }
                System.out.println("消费者取值成功,data:" + data);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                System.out.println("消费者已经结束");
            }
        }

    }
}

public class Test03 {
    public static void main(String[] args) throws InterruptedException {
        BlockingQueue<String> blockingQueue = new LinkedBlockingQueue<String>();
        ProducerThread pThread = new ProducerThread(blockingQueue);
        ConsumerThread cThread = new ConsumerThread(blockingQueue);
        pThread.start();
        cThread.start();
        Thread.sleep(200);
        pThread.stopThread();
    }
}
